//
//  HBRegisterCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/11/26.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBRegisterCtrl.h"
#import "HBIndexCtrl.h"
#import "CheckValid.h"
#import "HBSetPasswordCtrl.h"
#import "HBAgreementCtrl.h"
#import "NetCenter.h"
#import "HBTabBarViewController.h"
#import "HBGetRegMobileCodeInfo.h"
#import "HBGetRegMobileCodeParam.h"
#import "HBGetRegMobileCodeParser.h"
#import "HBCheckPwdMobileCodeParam.h"
#import "HBCheckPwdMobileCodeParser.h"
#import "HBCheckRegMobileCodeParam.h"
#import "HBCheckRegMobileCodeParser.h"

@interface HBRegisterCtrl ()<UITextFieldDelegate>
{
    NSMutableArray* ctrlArr ;
    BOOL isFlag;
    NSString* phoneText;
}
@property (strong, nonatomic) NSString* verCode;
@property (strong, nonatomic) NSString* phoneNum;
@property (assign, nonatomic) BOOL isClicked;

@property (weak, nonatomic) IBOutlet UILabel *alertLabel;
@property (weak, nonatomic) IBOutlet UITextField *verCodeField;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumFiled;
@property (weak, nonatomic) IBOutlet UIButton *reCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *cleanBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *alertLabelH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *alertToTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *subBtnToTop;

- (IBAction)reGetVerCode:(UIButton *)sender;
- (IBAction)agreeBtn:(UIButton *)sender;
- (IBAction)submitAction:(id)sender;
- (IBAction)cleanAction:(id)sender;
- (IBAction)goService:(id)sender;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *reCodeBtnW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLineV;
@property (nonatomic, strong) UITextRange* previousSelection;
@property (nonatomic, strong) NSString*    previousTextFieldContent;
@property (nonatomic) BOOL isFirstGetCode;
@end

@implementation HBRegisterCtrl

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
//    
//     self.navigationController.navigationBarHidden = NO;
//    if (self.navigationController.viewControllers[0] == self) {
//        self.navigationController.navigationBarHidden = NO;
//    }else{
//        self.navigationController.navigationBarHidden = YES;
//    }
//    [self buildLayout];
    
    // 禁用 iOS7 返回手势
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//    }
//    self.navigationController.navigationBarHidden = YES;
    if (self.viewJumping == isFromLinkPage) {
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
        self.navigationItem.leftBarButtonItem = leftItem;
        [self showDoneWithTitle:@"跳过"];
    }
    if (isIphone4or5) {
       self.topLineV.constant = -126;
    }else{
         self.topLineV.constant = - 206;
    }
    isFlag = NO;
    self.cleanBtn.alpha = 0;
    self.agreeBtn.selected = YES;
    self.phoneNumFiled.text = @"";
    self.verCodeField.text = @"";
    [self setBtnNoPress];
    [self makeTime];
    

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isFirstGetCode = YES;

}
- (void)buildLayout{
//    [super viewWillAppear:YES];
    self.title = @"注册";
    self.submitBtn .enabled = NO;
    [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Selected] forState:UIControlStateHighlighted];
    
    [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.verCodeField.delegate = self;
    self.phoneNumFiled.delegate = self;
    self.phoneNumFiled.keyboardType = UIKeyboardTypeNumberPad;
    [self setTextFieldPlaceHolder:self.phoneNumFiled withString:@"请输入11位手机号码"];
    [self setTextFieldPlaceHolder:self.verCodeField withString:@"请输入验证码"];
 
    [self.phoneNumFiled addTarget:self action:@selector(textFieldEidt:) forControlEvents:UIControlEventEditingChanged];
    [self.verCodeField addTarget:self action:@selector(textFieldEidt:) forControlEvents:UIControlEventEditingChanged];
    self.reCodeBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = 10;
    self.reCodeBtn.layer.cornerRadius = 4;
    
}


- (void)doDone{
    HBTabBarViewController *tab = [[HBTabBarViewController alloc]init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tab;
}

- (void)textFieldEidt:(UITextField*)textField{
    [self reSetAlertLabelConstant];
    self.alertLabel.text = @"";
    
    if (self.phoneNumFiled == textField) {
        //第几次输入
        NSUInteger targetCursorPosition =[textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
        
        NSString* nStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString* preTxt = [self.previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        char editFlag = 0;
        if (nStr.length <= preTxt.length) {
            editFlag = 0;
//            LLog(@"删除第%li个",(long)targetCursorPosition+1);
            if (targetCursorPosition == 0) {
                [UIView animateWithDuration:0.25 animations:^{
                    self.cleanBtn.alpha = 0;
                }];
                
            }
        }else {
            editFlag = 1;
//            LLog(@"增加第%li个",(long)targetCursorPosition+1);
            if (targetCursorPosition == 1) {
                [UIView animateWithDuration:0.25 animations:^{
                  self.cleanBtn.alpha = 1;
                }];
                
            }
        }
    }
}

- (void)setTextFieldPlaceHolder:(UITextField*)textField withString:(NSString *)string {
    [textField setPlaceholder:string];
    if (isIphone4or5) {
        textField.font = [UIFont systemFontOfSize:14];
    }else{
        textField.font = [UIFont systemFontOfSize:15];
    }
    textField.textColor = [LCCommon getColor:@"ffffff"];
    [textField setValue:[LCCommon getColor:@"5e5e5f"] forKeyPath:@"_placeholderLabel.textColor"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma  mark TextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    self.previousTextFieldContent = textField.text;
    self.previousSelection = textField.selectedTextRange;
    
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.phoneNumFiled == textField){
        if ([toBeString length] > 10){
            textField.text = [toBeString substringToIndex:11];
            [textField resignFirstResponder];
            if ([CheckValid isValidatePhone:self.phoneNumFiled.text]) {
                [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"EFE572"]];
                [self.reCodeBtn setEnabled:YES];
            }else{
                [self setAlertLabelConstantWithAlertString:@"您输入的手机号不正确"];
            }
        }else if([toBeString length] <= 10){
            [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"a8a8a8"]];
            [self.reCodeBtn setEnabled:NO];
        }
    }
    if (self.verCodeField == textField) {
        if ([toBeString length] > 5) {
            textField.text = [toBeString substringToIndex:6];
            [textField resignFirstResponder];
            if ([CheckValid isOnlyNumber:self.verCodeField.text]) {
                if ([self.phoneNumFiled.text length] == 11 && self.agreeBtn.selected == YES) {
                    [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Normal] forState:UIControlStateNormal];
                    [self.submitBtn setEnabled:YES];
                }else{
                    [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Disable] forState:UIControlStateDisabled];
                    [self.submitBtn setEnabled:NO];
                }
            }else{
                [self setAlertLabelConstantWithAlertString:@"验证码只能为数字"];
                [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Disable] forState:UIControlStateDisabled];
                [self.submitBtn setEnabled:NO];
            }
        }else if([toBeString length] <= 5){
            [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Disable]];
            [self.submitBtn setEnabled:NO];
        }
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    int offset = frame.origin.y +20 - (self.view.frame.size.height - 216.0 -60 -64);
    [UIView animateWithDuration:0.3 animations:^{
        //当textField的frame被键盘覆盖后
        if(offset > 0){
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }
    }];
}

- (void)setBtnNoPress{
    [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Disable] forState:UIControlStateNormal];
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = 4.0;
    self.submitBtn.enabled = NO;
}
- (void)setBtnDoPress{
    [self.submitBtn setBackgroundColor:[LCCommon getColor:Btn_Normal] forState:UIControlStateNormal];
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = 4.0;
    self.submitBtn.enabled = YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.phoneNumFiled resignFirstResponder];
    [self.verCodeField resignFirstResponder];
    [UIView animateWithDuration:0.25 animations:^{
       [self.view setFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    }];
}

- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:REGIST_CODE_TIME] longLongValue];
        
        if (timeLast <= 0){
            self.reCodeBtn.enabled = YES;
            [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
            self.reCodeBtn.backgroundColor = [LCCommon getColor:@"a8a8a8"];
            [self.view layoutIfNeeded];
            [UIView animateWithDuration:0.25 animations:^{
               self.reCodeBtnW.constant = 105;
                [self.view layoutIfNeeded];
            }];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            
            LLog(@"phoneText ----  %@",phoneText);
            LLog(@"%@",self.phoneNumFiled.text);
            
            if (([self.phoneNumFiled.text  length] == 11) && [self.phoneNumFiled.text isEqualToString:phoneText] ){
                [self.reCodeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                [self.reCodeBtn setTitle:@"重新获取验证码" forState:UIControlStateDisabled];
                self.reCodeBtn.enabled = YES;
                self.reCodeBtn.backgroundColor = [LCCommon getColor:@"EFE572"];
            }else{
                self.reCodeBtn.enabled = NO;
                [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
                self.reCodeBtn.backgroundColor = [LCCommon getColor:@"a8a8a8"];
            }
            if (self.isFirstGetCode)
            {
                [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"a8a8a8"]];
                [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
            }
            return;
        }
        self.reCodeBtn.enabled = NO;
        [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"a8a8a8"]];
        phoneText = self.phoneNumFiled.text;
        [self.reCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.reCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });

    
}

- (void)setTimerDefault{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 60] forKey:REGIST_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma  mark buttonClicked
- (IBAction)goService:(id)sender {
    LLog(@"注册服务协议");
    HBAgreementCtrl* agreeMentVC =[[HBAgreementCtrl alloc] init];
    [self.navigationController pushViewController:agreeMentVC animated:YES];
}
- (IBAction)cleanAction:(id)sender {
   self.phoneNumFiled.text = @"";
    [UIView animateWithDuration:0.25 animations:^{
        self.cleanBtn.alpha = 0;
        [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"a8a8a8"]];
    }];
}
- (IBAction)agreeBtn:(UIButton *)sender {
    [self reSetAlertLabelConstant];
    sender.selected = !sender.selected;
    self.agreeBtn.selected = sender.selected;
    if (self.agreeBtn.selected){
        if ((self.phoneNumFiled.text.length > 10)&&(self.verCodeField.text.length >5 ) ){
            [self setBtnDoPress];
        }
    }else{
        [self setBtnNoPress];
    }
}
- (void)setAlertLabelConstantWithAlertString:(NSString*)alertString{
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.35 animations:^{
        LLog(@"alertLabelH--%lf,alertToTop--%lf,subBtnToTop--%lf",self.alertLabelH.constant,self.alertToTop.constant,self.subBtnToTop.constant);
        self.alertLabelH.constant = 20.0;
        self.alertToTop.constant = 15.0;
        self.subBtnToTop.constant = 15.0;
        self.alertLabel.text = alertString;
        [self.view layoutIfNeeded];
    }];
}

- (void)reSetAlertLabelConstant{
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.35 animations:^{
        LLog(@"alertLabelH--%lf,alertToTop--%lf,subBtnToTop--%lf",self.alertLabelH.constant,self.alertToTop.constant,self.subBtnToTop.constant);
        self.alertLabelH.constant = 5.0;
        self.alertToTop.constant = 9.0;
        self.subBtnToTop.constant = 3.0;
        self.alertLabel.text = @"";
        [self.view layoutIfNeeded];
    }];
}

- (IBAction)submitAction:(id)sender {
    if (![CheckValid isValidatePhone:self.phoneNumFiled.text]) {
        [self setAlertLabelConstantWithAlertString:@"手机号不正确"];
        return;
    }
    
    HBCheckRegMobileCodeParam* param = [[HBCheckRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNumFiled.text;
    param.mobileCode = self.verCodeField.text;
    HBCheckRegMobileCodeParser* parser = [[HBCheckRegMobileCodeParser alloc] init];
    [CustomLoadingView showHudToView:self.view];
    [NetCenter postDataFromURL:Method_checkRegMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code == 0) {
            HBSetPasswordCtrl* setPassVC = [[HBSetPasswordCtrl alloc] init];
            setPassVC.phoneNum = self.phoneNumFiled.text;
            setPassVC.mobileCode = self.verCodeField.text;
            [self.navigationController pushViewController:setPassVC animated:YES];
        }else{
            [self setAlertLabelConstantWithAlertString:myResult.message];
        }
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR(error.description);
    }];
}

- (IBAction)reGetVerCode:(UIButton *)sender {
    if (![CheckValid isValidatePhone:self.phoneNumFiled.text]) {
        [self setAlertLabelConstantWithAlertString:@"手机号不正确"];
        self.phoneNumFiled.text = @"";
        self.verCodeField.text = @"";
        [self.phoneNumFiled becomeFirstResponder];
        return;
    }
    [self reSetAlertLabelConstant];
//    self.isClicked = YES;
//    if (self.isClicked) {
//            [self.reCodeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
//            self.reCodeBtnW.constant = 120;
//    }
    HBGetRegMobileCodeParam* param = [[HBGetRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNumFiled.text;
    param.gid = [self getGID];
    HBGetRegMobileCodeParser* parser = [[HBGetRegMobileCodeParser alloc] init];
    [CustomLoadingView showHudToView:self.view];
    [NetCenter postDataFromURL:Method_getRegMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        
        [CustomLoadingView hideHudForView:self.view];
        self.isFirstGetCode = NO;
          [self makeTime];
        if (myResult.code == 0) {
            LLog(@"验证码已发送");
            HBGetRegMobileCodeInfo* info = (HBGetRegMobileCodeInfo*)myResult.result;
            //测试用
            self.verCodeField.text = info.mobileCode;
            self.verCode = info.mobileCode;
            self.phoneNum = self.phoneNumFiled.text;
            LLog(@"%@",self.phoneNum);
            [self setTimerDefault];
          
         
        }
        if (myResult.code == 1) {
            DISSMISS_ERR(myResult.message);
            [self.reCodeBtn setBackgroundColor:[LCCommon getColor:@"a8a8a8"] forState:UIControlStateDisabled];
            [self.reCodeBtn setEnabled:NO];
            [self.reCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
           
            
        }
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR(error.description);
    }];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeTime) object:nil];
    [self reSetAlertLabelConstant]; 
}

- (NSString*)getGID{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}


@end
